//
//  FBtManager.m
//  JwPackDemo
//
//  Created by 陈警卫 on 2025/8/13.
//

#import "FBtManager.h"

@interface FBtManager ()

@end

@implementation FBtManager

+ (FBtManager *)shared {
    static FBtManager *shared;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        shared = [[FBtManager alloc] initPrivate];
    });
    return shared;
}

- (instancetype)init {
    return [[self class] shared];
}

- (instancetype)initPrivate {
    self = [super init];
    if (self) {
        [self setupData];
    }
    return self;
}

- (void)setupData {
    
    self.btSession = [[FBtSession alloc] init];
    
    CXBtConfig *config = [[CXBtConfig alloc] init];
    self.btCore = [[CXBtCore alloc] initWithConfig:config];
    
    __weak typeof(self) wself = self;
    self.btCore.didState = ^(CXBtState state) {
        
    };
    self.btCore.didScanedPeri = ^(CXBtPeriModel *periModel) {
        
    };
    self.btCore.didDisconncetPeri = ^(CXBtPeriModel *periModel) {
        [wself disconncetPeriAction:periModel];
    };
    self.btCore.didNotifedPeri = ^(CXBtPeriModel *periModel) {
        [wself notifedPeriAction:periModel];
    };
    self.btCore.didNotifedValue = ^(CXBtPeriModel *periModel, NSData *data) {
        [wself notifedValueAction:periModel data:data];
    };
}

/// 自动连接外设
/// name 外设名称
- (void)autoNotifyWithName:(NSString *)name {
    // 断开连接 保持单一连接
    [self.btCore disconnectAll];
    
    CXBtPeriModel *periModel = [[CXBtPeriModel alloc] init];
    periModel.scanModel.connectName = name;
    periModel.scanModel.serviceUUIDs = [NSMutableSet setWithArray:@[[CBUUID UUIDWithString:@"00FF"]]];
    periModel.scanModel.writeUUIDs = [NSMutableSet setWithArray:@[[CBUUID UUIDWithString:@"FF01"]]];
    periModel.scanModel.notifUUIDs = [NSMutableSet setWithArray:@[[CBUUID UUIDWithString:@"FF01"]]];
    
    [self.btCore autoNotifyPeriModel:periModel comple:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

/// 当前连接外设(订阅成功)
- (CXBtPeriModel *)currentPeriModel {
    CXBtPeriModel *periModel = nil;
    if (self.btCore.notifedPeriModels.count > 0) {
        periModel = self.btCore.notifedPeriModels.firstObject;
    }
    return periModel;
}

#pragma mark - func

- (void)disconncetPeriAction:(CXBtPeriModel *)periModel {
    [self.btSession resetBtSession];
}

- (void)notifedPeriAction:(CXBtPeriModel *)periModel {
    [self.btSession resetBtSession];
}

- (void)notifedValueAction:(CXBtPeriModel *)periModel data:(NSData *)data {
    [self.btSession receiveData:data];
}




@end
